package com.zhenyi.websocket.core.ws;

import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import cn.hutool.core.lang.Singleton;
import cn.hutool.json.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	// ChannelGroup allChannels = new DefaultChannelGroup("ChannelGroups",
	// GlobalEventExecutor.INSTANCE);

	// protected final Hashids hashId = new Hashids("fenda", 6);
	protected Cache cache = Redis.use();
	private ChannelGroup allChannels = Singleton.get(WSServer.class).allChannels;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		String text = msg.text();
		String wsUid = ctx.channel().id().asLongText();
		try {
			JSONObject jsonObject = new JSONObject(text);
			String code = jsonObject.getStr("code");
			if (StrKit.isBlank(code)) {
				return;
			}
			if (code.equals("101")) {
				String token = jsonObject.getStr("token");
				if (StrKit.isBlank(token)) {
					return;
				}
				String uid = cache.get(token);
				if (StrKit.isBlank(uid)) {
					return;
				}
				cache.hset(WSServer.WS_FIELD, wsUid, token);
				cache.hset(WSServer.WS_FIELD_MAP, token, wsUid);
			}
			// Channel channel = ctx.channel();
			// System.out.println("read0");
			// System.out.println(channel.remoteAddress() + ": " + msg.text());
			Ret ret = Ret.by("status", 200);
			ret.set("uid", wsUid);
			ctx.channel().writeAndFlush(new TextWebSocketFrame(ret.toJson()));
		} catch (Exception e) {
			LogKit.warn("json error", e);
			LogKit.warn(text);
		}

	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		try {
			// System.out.println("连接" + ctx.channel().id().asLongText());
			allChannels.add(ctx.channel());
			// int size = allChannels.size();
			ctx.channel().writeAndFlush(new TextWebSocketFrame(ctx.channel().id().asLongText()));
			// allChannels.writeAndFlush(new TextWebSocketFrame(size + "来自服务端:
			// "));
			String wsUid = ctx.channel().id().asLongText();
			Ret ret = Ret.by("status", 200);
			ret.set("uid", wsUid);
			ctx.channel().writeAndFlush(new TextWebSocketFrame(ret.toJson()));
			// cache.hset(, field, value)
			// cache.setex("", seconds, value)
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		String wsUid = ctx.channel().id().asLongText();
		// System.out.println("用户下线: " + wsUid);
		String token = cache.hget(WSServer.WS_FIELD, wsUid);
		cache.hdel(WSServer.WS_FIELD, wsUid);
		cache.hdel(WSServer.WS_FIELD_MAP, token);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().close();
	}
}